/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-04
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-07
 * @Description: 程序入口
 */
import 'package:chat_client/repositories/preferences_repository.dart';
import 'package:chat_client/repositories/hive_repository.dart';
import 'package:flutter/material.dart';
import 'screens/home_screen.dart';
import 'screens/auth/login_screen.dart';
import 'theme.dart';
import 'package:chat_client/services/auth_service.dart';

void main() async {
  // 确保 Flutter 的引擎已经初始化, 异步操作能在应用启动时正确执行
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 HiveService 工具类
  await HiveService.initHive();

  // 初始化 Preferences 工具类
  await Preferences.init();

  AuthService authService = AuthService.instance;

  runApp(MyApp(authService: authService));
}

// MyApp 组件是应用的根组件，它负责管理应用的主题和路由
class MyApp extends StatelessWidget {
  final AuthService _authService;

  const MyApp({super.key, required AuthService authService})
      : _authService = authService;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Chat App',
      theme: AppThemes.lightTheme,
      darkTheme: AppThemes.darkTheme,
      themeMode: ThemeMode.light,
      home: _buildHomeScreen(),
    );
  }

  Widget _buildHomeScreen() {
    return FutureBuilder<bool>(
      future: _authService.reconnect(), // 判断登录状态,并尝试自动登录
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const LoadingScreen();
        }

        if (snapshot.hasError || !snapshot.hasData || !snapshot.data!) {
          // return const HomeScreen();
          return const LoginScreen();
        }

        return const HomeScreen();
      },
    );
  }
}

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: CircularProgressIndicator(), // 显示加载进度条
      ),
    );
  }
}
